package handler

import (
	"fmt"
	config "goweb/config"
	"goweb/service"
	"html/template"
	"net/http"
)

var loginURL = config.GetDir() + "html/login.html"

//Login 登录
func Login(w http.ResponseWriter, r *http.Request) {

	switch r.Method {
	case "POST":
		r.ParseForm()
		loginName := r.PostFormValue("loginName")
		pwd := r.PostFormValue("pwd")
		user, err := service.GetUserByName(loginName, pwd)
		if nil != err {
			template.Must(template.ParseFiles(loginURL)).ExecuteTemplate(w, "message", err.Error())
		} else {
			cookie := http.Cookie{Name: "userId", Value: user.UserID}
			nameCookie := http.Cookie{Name: "name", Value: user.Name}
			http.SetCookie(w, &cookie)
			http.SetCookie(w, &nameCookie)
			http.Redirect(w, r, "/index", http.StatusFound)
		}

		break
	case "GET":
		dir := config.GetDir()
		fmt.Println(dir)
		template.Must(template.ParseFiles(loginURL)).ExecuteTemplate(w, "message", "")
		break

	}
}
